import userApi from '@/api/auth/userApi.js'
import utils from '@/common/utils.js'
import {defaultPswd, emailReg, phoneReg} from '@/common/constant.js'
import {gender} from '@/view/auth/dict'
import roleApi from '@/api/auth/roleApi'

const genderDict = gender;

export default {
  name: "User",
  filters:{
    genderFormat(gender){
      return (genderDict.list.find(e => e.value === gender)|| {}).label
    }
  },
  data() {
    const checkPhone = function(rule, value, callback){
      if(!value){
        callback()
      }
      if(phoneReg.test(value)){
        callback()
      }else{
        callback(new Error('请输入正确的电话'))
      }
    }
    const checkEmail = function (rule, value, callback) {
      if(!value){
        callback()
      }
      if(emailReg.test(value)){
        callback()
      }else{
        callback(new Error('请输入正确的邮箱'))
      }
    }
    return {
      // 是否可见
      formVisible: false,
      // 表单标题
      formTitle: '',
      // 表单状态 edit,insert
      formState: '',
      // 表单数据
      formData: {
        id: '',
        username: '',
        name: '',
        gender: '',
        email: '',
        phone: '',
        birth: '',
        headPic: '',
      },
      // ePage的表格数据
      tableData: [],
      currentUserId: '',
      // 查询项配置
      searchConf: [
        {
          label: '登录名',
          prop: 'username',
          type: 'input'
        },
        {
          label: '姓名',
          prop: 'name',
          type: 'input'
        },
      ],
      // 表格配置
      tableConf: {
        multiple: true,
        operateWidth: '250px',
        defaultSort: {prop: 'createTime', order: 'descending'},
        columns: [
          {
            label: '登录名',
            prop: 'username',
            sortable: true,
          },
          {
            label: '姓名',
            prop: 'name',
            sortable: true,
          },
          {
            label: '性别',
            prop: 'gender',

          },
          {
            label: '手机号',
            prop: 'phone',
          },
          {
            label: '角色',
            prop: 'roles',
          },
          {
            label: '岗位',
            prop: 'postId',
          },
        ]
      },
      // 按钮配置
      buttons: [
        {label: "详情", event: "detail", type: "primary", isLink: true},

        /*{label: "新增", event: "insert", type: "primary"},
        {label: "删除", event: "del", type: "danger"},

        {label: "修改", event: "edit", type: "primary", isLink: true},
        {label: "绑定角色", event: "bindRole", type: "primary",isLink: true},
        {label: "重置密码", event: "resetPassword", type: "primary",isLink: true}*/
      ],
      // 表单验证规则
      rules: {
        username: [{required: true, message: "请输入登录名", trigger: "blur"},{}],
        name: [{required: true, message: "请输入姓名", trigger: "blur"}],
        postId: [{required: true, message: "请选择岗位", trigger: "blur"}],
        headPic: [{required: true, message: "请输入头像", trigger: "blur"}],
        phone: [{ required: false, validator: checkPhone, trigger: "blur" }],
        email: [{ required: false, validator: checkEmail, trigger: "blur" }],
      },
      map:{
        gender:{},
        postTree:[],
      },
      roleVisible: false,
      role:{
        // 全部角色
        list: [],
        // 所属角色
        selectedRole:[],
      },
      // 详情是否可见
      detailVisible: false,
      detailData:{
        username: '',
        name: '',
        gender: '',
        email: '',
        phone: '',
        birth: '',
        headPic: '',
        postId:'',
      }
    }
  },
  methods: {
    roleClose(){
      this.roleVisible = false
    },
    roleConfirm(){
      userApi.setRoles({userId: this.currentUserId,roleIds: this.role.selectedRole}).then(res=>{
        this.$message.success('保存成功')
        this.roleClose()
      })
    },
    // 初始化数据
    initData(){
      this.map.gender = genderDict.list
    },
    // 绑定角色
    bindRole({row}){
      this.currentUserId = row.id
      userApi.listRoleByUserId({userId: this.currentUserId}).then(res=>{
        this.role.selectedRole = res.data.map(e=>{
          return e.id
        })
      }).catch(err=>{
        return
      })
      this.$rq.list(roleApi.url).then(res=>{
        this.role.list = res.data
      }).catch(err=>{
        return
      })
      this.roleVisible = true
    },
    // 获取列表数据
    setData(params, callback) {
      this.$rq.query(userApi.url, params).then(res => {
        callback({total: res.data.total, data: res.data.rows})
      }).catch(err => {
        this.tableData = []
      })
    },
    // 获取表格数据
    page(){
      this.$refs.page.getData()
    },
    // 重置表格查询
    reset(){
      this.$refs.page.reset()
    },
    // 清空表单
    formClear(){
      // 清空校验
      if(this.$refs.form){
        this.$refs.form.clearValidate()
        this.$refs.form.resetFields()
      }
      // 重新赋值
      this.formData = {
        id: '',
        username: '',
        name: '',
        gender: '',
        email: '',
        phone: '',
        birth: '',
        headPic: '',
        postId:'',
      }
    },
    // 保存事件
    formSave(){
      this.$refs.form.validate(valid=>{
        if(valid){
          let data = utils.formatObj(this.formData)
          if(this.formState === 'edit'){
            this.$rq.updateById(userApi.url,data).then(res=>{
              this.$message.success('保存成功')
              this.formVisible = false
              this.page()
            })
          }else if(this.formState ==='insert'){
            this.$rq.insert(userApi.url,{...data,...{password: defaultPswd}}).then(res=>{
              this.$message.success('保存成功')
              this.formVisible = false
              this.page()
            })
          }
        }
      })
    },
    // 表单关闭
    formClose(){
      this.formVisible = false
    },
    // 设置表单数据
    formSet(data){
      this.formData.id = data.id
      this.formData.username = data.username
      this.formData.name = data.name
      this.formData.gender = data.gender
      this.formData.email = data.email
      this.formData.phone = data.phone
      this.formData.birth = data.birth
      this.formData.headPic = data.headPic
      this.formData.postId = data.postId
    },
    // ePage中的操作按钮,会相应的触发其event对应的事件
    handleEvent(event, payload) {
      if (this[event] instanceof Function) {
        this[event](payload);
      } else {
        // this.$message.warning('按钮无效')
      }
    },
    // 删除方法
    del({selection}) {
      if (selection.length) {
        let ids = selection.map(e => e.id)
        this.$confirm('确认删除?', {
          title: '提示',
          confirmButtonText: '删除',
          type: 'warning',
          beforeClose: (action, instance, done) => {
            if (action == 'confirm') {
              instance.confirmButtonLoading = true;
              instance.confirmButtonText = '执行中...';
              this.$rq.deleteByIds(userApi.url, ids).then(res => {
                this.$message.success('删除成功')
                this.page()
              }).finally(()=>{
                done()
                instance.confirmButtonLoading = false;
              })
            }else{
              done()
            }
          }
        })
      } else {
        this.$message.warning('请至少选择一行')
      }
    },
    // 编辑
    edit({row}) {
      this.formTitle='编辑'
      this.formState = 'edit'
      this.formVisible = true
      this.formClear()
      row.gender=row.gender
      this.formSet(row)
    },
    // 新增
    insert({row}){
      this.formTitle='新增'
      this.formState = 'insert'
      this.formVisible = true
      this.formClear()
    },
    // 详情
    detail({row}) {
      this.detailVisible = true
      this.detailData = row
    },
    // 关闭详情
    detailClose(){
      this.detailVisible = false
    },
    // 重置密码
    resetPassword({row}){
      this.$confirm('确认重置密码?', {
        title: '提示',
        confirmButtonText: '确认',
        type: 'warning',
        callback: (action) => {
          if (action == 'confirm') {
            // userApi.alterPassword({id:row.id, password: {defaultPswd}}).then(_=>{
            userApi.alterPassword({id:row.id,password:defaultPswd}).then(_=>{
              this.$message.success('重置成功')
            }).catch(_ => {
            })
          }
        }
      })
    }
  },
  mounted() {
    this.page()
  },
  created() {
    this.initData()
  }
};
